﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace RStein.PosterousReader.WP.UI
{
  public class ProgressBarEx : ProgressBar
  {

    public static readonly DependencyProperty IsVisibleProperty =
        DependencyProperty.Register("IsVisible", typeof(bool), typeof(ProgressBarEx), new PropertyMetadata(false,
                                                                                                           showHideElements));

    public static readonly DependencyProperty AttachedContentProperty =
        DependencyProperty.Register("AttachedContent", typeof(UIElement), typeof(ProgressBarEx), new PropertyMetadata(null,
                                                                                                                      handleAttachedContentChanged));


    public ProgressBarEx()
    {
    }



    public bool IsVisible
    {
      get
      {
        return (bool) GetValue(IsVisibleProperty);
      }
      set
      {
        SetValue(IsVisibleProperty, value);                
      }
    }



    public UIElement AttachedContent
    {
      get
      {
        return (UIElement) GetValue(AttachedContentProperty);
      }
      set
      {
        SetValue(AttachedContentProperty, value);
      }
    }
            
    
    private static void showHideElements(DependencyObject dpObject, DependencyPropertyChangedEventArgs dpe)
    {
      var progressBar = dpObject as ProgressBarEx;
      if (progressBar  == null)
      {
        return;
      }
      
      showHideInner((bool) dpe.NewValue, progressBar);

    }

    private static void showHideInner(bool isVisible, ProgressBarEx progressBar)
    {      
      progressBar.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;

      UIElement attachedContent = progressBar.AttachedContent;
      if (attachedContent == null)
      {
        return;
      }

      progressBar.AttachedContent.Visibility = (isVisible ? Visibility.Collapsed : Visibility.Visible);
    }

    private static void handleAttachedContentChanged(DependencyObject dpObject, DependencyPropertyChangedEventArgs dpe)
    {
      var progressBar = dpObject as ProgressBarEx;
      if (progressBar == null)
      {
        return;
      }

      showHideInner(progressBar.IsVisible, progressBar);
    }

  }
}
